﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 全选与反选联动
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 防止在更新 CheckBox 状态时触发事件循环;确保状态更新是原子操作
        /// </summary>
        private bool isUpdatingSelection = false;


        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 全选 CheckBox 的 Checked 事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectAllCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (isUpdatingSelection) return;

            isUpdatingSelection = true;

            // 设置所有子 CheckBox 为选中状态
            foreach (var child in itemsPanel.Children)
            {
                if (child is CheckBox checkBox && checkBox != sender)
                {
                    checkBox.IsChecked = true;
                }
            }

            isUpdatingSelection = false;
        }

        /// <summary>
        /// 全选 CheckBox 的 Unchecked 事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectAllCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (isUpdatingSelection) return;

            isUpdatingSelection = true;

            // 设置所有子 CheckBox 为未选中状态
            foreach (var child in itemsPanel.Children)
            {
                if (child is CheckBox checkBox && checkBox != sender)
                {
                    checkBox.IsChecked = false;
                }
            }

            isUpdatingSelection = false;
        }

        /// <summary>
        /// 子 CheckBox 状态变化事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ItemCheckBox_Changed(object sender, RoutedEventArgs e)
        {
            if (isUpdatingSelection) return;

            isUpdatingSelection = true;

            // 检查是否所有子项都被选中
            bool allChecked = true;

            foreach (var child in itemsPanel.Children)
            {
                if (child is CheckBox checkBox && checkBox.IsChecked != true)
                {
                    allChecked = false;
                    break;
                }
            }

            // 更新全选 CheckBox 的状态
            // 只有当所有子项都选中时，全选才选中
            // 其他情况（包括部分选中或全部未选中）全选都未选中
            selectAllCheckBox.IsChecked = allChecked;

            isUpdatingSelection = false;
        }

    }
}